package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.activity.BaseActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.adapter.ProfileFollowListAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.model.UserModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * create by nick
 * 我的->关注的人和粉丝列表
 */
public class FollowListActivity extends BaseActivity implements ProtoCallBack, BaseQuickAdapter.OnItemChildClickListener {


    private RecyclerView rcv_follow_list;
    private int count=20;
    private long start;
    private String loadFollowListConmand;
    private ProfileFollowListAdapter adapter;
    private List<UserModel> userModels;
    public static final int TYPE_FOLLOW=1;
    public static final int TYPE_FANS=2;
    private static final String TYPE_TAG="type_tag";
    private static final String UID_TAG="uid_tag";
    private long uid;
    private TwinklingRefreshLayout follow_trl_refresh;
    private FollowControl followControl;
    private IMYTBASObject followChangeListener;

    public static void start(Context context,int type,long uid) {
    Intent starter = new Intent(context, FollowListActivity.class);
    starter.putExtra(TYPE_TAG,type);
    starter.putExtra(UID_TAG,uid);
    context.startActivity(starter);
}

    @Override
    protected int getLayoutId() {
        return R.layout.activity_follow_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        uid=getIntent().getLongExtra(UID_TAG,0);
        setTitle(isFans()?getString(R.string.mine_fans_list):getString(R.string.mine_follow_list));
        rcv_follow_list = $(R.id.rcv_follow_list);
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivider(this,rcv_follow_list);
        userModels = new ArrayList<>();

        follow_trl_refresh = $(R.id.follow_trl_refresh);
        RefreshView headerView = new RefreshView(this);
        follow_trl_refresh.setHeaderView(headerView);
        follow_trl_refresh.setBottomView(new LoadingView(this));
        follow_trl_refresh.setEnableLoadmore(true);
        follow_trl_refresh.setEnableOverScroll(false);
        follow_trl_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                start=0;
                loadMineFollowList();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadMore();
            }
        });

        loadMineFollowList();
        registerSocketNotify();
        MobclickAgent.onEvent(FollowListActivity.this, isFans() ? "follower_open" : "attention_open");
    }

    private void loadMineFollowList(){
        if (isFans()){
            loadFollowListConmand = ProtoRequestHelper.task(ProtoHttpFactory.getMineFansList(count,start,uid)).setTag(this.hashCode()).request(this);
        }else{
            loadFollowListConmand = ProtoRequestHelper.task(ProtoHttpFactory.getMineFollowList(count,start,uid)).setTag(this.hashCode()).request(this);
        }


    }

    @Override
    public void onRequestSuccess(String command, String data) {
        Log.e("follow_list", "onRequestSuccess: "+data );
        refreshFinish();
        if (loadFollowListConmand.equals(command)){
            Result<List<UserModel>> listResult = JSON.parseObject(data,new TypeReference<Result<List<UserModel>>>(){}.getType());
            if (listResult.result == CodeSuccess){
                if (start==0){
                    userModels.clear();
                }
                userModels.addAll(listResult.data);
                bindAdapter();

            }
        }

    }

    @Override
    public void onRequestError(String command, int code, String message) {
        Log.e("follow_list", "onRequestError: "+message );
        refreshFinish();


    }
    private void bindAdapter(){
        if (adapter==null){
            adapter= new ProfileFollowListAdapter(userModels);
            rcv_follow_list.setAdapter(adapter);
            adapter.setOnItemChildClickListener(this);
            adapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.view_load_layout,null));
        }else{
            adapter.setNewData(userModels);
            adapter.notifyDataSetChanged();
        }
    }


    private boolean isFans(){
        return TYPE_FANS==getIntent().getIntExtra(TYPE_TAG,-1);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (!isFans()){
            MobclickAgent.onEvent(FollowListActivity.this, "attention_click_content");
        }

        switch (view.getId()){
            case R.id.iv_head_img_follow:
            case R.id.tv_name_follow:
                ProfileActivity.start(this,userModels.get(position).getUid());
                break;
            case R.id.cb_profile_follow:
                if (followControl==null){
                    followControl = new FollowControl();
                }
                followControl.followChanged(getApplicationContext(),userModels.get(position),false);
                break;
        }

    }
    /**
     * 完成刷新
     */
    public void refreshFinish() {
        if (follow_trl_refresh != null) {
            follow_trl_refresh.finishRefreshing();
            follow_trl_refresh.finishLoadmore();
        }
    }
    public void loadMore() {
        start = userModels.size();
        loadMineFollowList();
    }

    protected void registerSocketNotify() {
        followChangeListener = new IMYTBASObject(false);
        followChangeListener.stringCommand = EventHelper.EVENT_FOLLOW_UICHANGE;
        followChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                refreshFollowStatus(object.stringData);
            }
        });
        followChangeListener.addEventListenWithTBASObject();

    }
    private void refreshFollowStatus(String uidStr){
        boolean isFollow = true;
        int sp = uidStr.indexOf("#");
        if (sp > 0) {
            uidStr = uidStr.substring(0, sp);
            isFollow = false;
        }
        int uid = Integer.parseInt(uidStr);
       int position =-1;
        if (userModels!=null){
            for (int i = 0; i < userModels.size(); i++) {
                if (userModels.get(i).getUid()==uid) {
                    position=i;
                    userModels.get(i).setMyFollow(isFollow);
                    break;
                }
            }
            final int finalPosition = position;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalPosition !=-1) {
                        adapter.notifyItemChanged(finalPosition);
                    }
                }
            });
        }


    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (followChangeListener != null) {
            followChangeListener.destroy();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}
